<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="700px"
    >
      <el-form
        :model="classForm"
        :rules="classFormRules"
        ref="classForm"
        label-width="100px"
      >
        <el-form-item label="班级名称" prop="className">
          <el-input
            minlength="2"
            maxlength="16"
            v-model="classForm.className"
            placeholder="请输入班级名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="所属年级" prop="initGrade">
          <el-select
            v-model="classForm.initGrade"
            placeholder="请选择年级"
            :disabled="mode === 'edit'"
          >
            <el-option
              v-for="cl in selectEnums.grade"
              :key="cl.id"
              :label="cl.name"
              :value="cl.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="dataFormSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addZb, editZb } from '@/api/setClass.js'
import cloneDeep from 'lodash/cloneDeep'

export default {
  data () {
    let validatePass = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5a-zA-Z0-9（）_-]*$/;
      if (!reg.test(value)) {
        callback(new Error('只支持输入汉字、数字、字母、（）、-、_'));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      title: '组建班级',
      classForm: {
        className: '',
        initGrade: '',
        classId: ''
      },
      classFormRules: {
        initGrade: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        className: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
          {
            required: true,
            trigger: 'blur',
            validator (rule, value, callback) {
              if (value.trim().length >= 2 && value.trim().length <= 16) {
                callback()
              } else {
                callback(new Error('名称长度范围需要在[2, 16]范围内'))
              }
            }
          },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  props: {
    mode: '',
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    gradeList: {
      type: Array,
      default: function () {
        return []
      }
    },
    schoolId: [Number, String]
  },
  watch: {
    selectEnums: {
      handler () {
        console.log('selectEnums', this.selectEnums)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    init (info) {
      this.classList = this.gradeList
      this.visible = true
      this.title = this.mode === 'add' ? '组建班级' : '编辑班级'
      console.log('init', this.mode, this.classInfo)
      if (this.mode === 'add') {
        this.classForm = this.$options.data().classForm;
        this.$nextTick(() => {
          this.$refs["classForm"].resetFields();
        });
      } else {
        this.classForm = info
      }
      console.log('init', this.mode, this.classForm)
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['classForm'].validate(valid => {
        if (valid) {
          this.submit(this.classForm)
        }
      })
    },
    async submit (e) {
      let params = {
        ...this.classForm,
        schoolId: this.schoolId
      }
      let res =
        this.mode === 'add'
          ? await addZb(params)
          : await editZb({
            ...params,
            classId: this.classForm.classId
          })
      if (res[0]) {
        return
      }
      let data = res[1]

      if (data && data.code === 0) {
        this.$message({
          message: this.mode === 'add' ? '新增班级成功！' : '编辑班级成功！',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$emit('refreshDataList', cloneDeep(this.classForm))
            this.$refs.classForm.resetFields()
            this.visible = false
            this.classForm = {
              className: '',
              initGrade: ''
            }
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
